import React, { PureComponent } from 'react';
import router from 'umi/router';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, message, Row, Modal, Select, Col, Steps, Button, Input, Radio, Divider } from 'antd';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper'; // 引入头部组件
import styles from '@/utils/utils.less';
import HOCSelect from '@/components/AntDesign/Select';
import AddEmpForm from '../../SocialService/SocialCard/AddEmpForm';
import AddEmpInfor from '../../SocialService/SocialCard/AddEmpInfor';
import AddMatInfor from '../../SocialService/SocialCard/AddMatInfor';

const { confirm } = Modal;
const FormItem = Form.Item;
const { Step } = Steps;
const { Option } = Select;
const steps = [
  {
    title: '查询员工',
    content: 'First-content',
  },
  {
    title: '发起办理',
    content: 'Second-content',
  },
];
const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 9,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 12,
    },
    md: { span: 7 },
  },
};
const formItemLayouts = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 8,
    },
    xl: { span: 8 },
    xxl: { span: 6 },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 16,
    },
  },
};
const RadioGroup = Radio.Group;
@connect(
  ({
    publicdata: { serviceTypeList },
    accuservicehandle: {
      sendData,
      empNameSelect,
      empNameList,
      elementArr,
      matFileDictItem,
      messageData,
      coltFlag,
    },
    loading,
  }) => ({
    // 对应的文件名：{方法名}
    elementArr,
    sendData,
    empNameList,
    empNameSelect,
    matFileDictItem,
    serviceTypeList,
    messageData,
    coltFlag,
    loading: loading.effects['accuservicehandle/fetchEmpNameList'] && loading.effects['accuservicehandle/addList'],
  })
)
class archivesAdd extends PureComponent {
  state = {
    current: 0,
    btnDis: true,
    refundFlag: 2,
    visNext: false,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'accuservicehandle/clearEmpName',
      payload: {},
    });
    dispatch({
      type: 'publicdata/serviceType',
      payload: { serType: 2 },
    });
    this.setState({
      refundFlag: 2,
    });
  }

  handleCancel = () => {};

  // 下一步
  prev = () => {
    const { current } = this.state;
    const currentStep = current - 1;
    this.setState({ current: currentStep, btnDis: true });
    const { dispatch } = this.props;
    dispatch({
      type: 'accuservicehandle/clearEmpName',
      payload: {},
    });
    this.setState({
      refundFlag: 2,
    });
  };

  baseData = () => {};

  // 获取服务类型
  serviceType = (value,KEY) => {
    console.log(value);
    this.setState({
      serTypeId: value,
      serTypeName: KEY.children,
    });
  };

  // 是否有返款
  refunds = e => {
    this.setState({
      refundFlag: e.target.value,
    });
  };

  // 提交运行
  saveUpdate = () => {
    const {
      location: { pathname },
      form,
    } = this.props;
    const tempUrl = pathname.split('/add')[0];
    form.validateFields({ force: true }, (err, values) => {
      if (!err) {
        const matlist = [];
        const accuSerHdl = {};
        const newValues = values;
        Object.keys(values).forEach(key => {
          if (key.indexOf('_') !== -1) {
            if (String(values[key].inpType) === '9') {
              let file = '';
              if (values[key].fileList && values[key].fileList.length) {
                values[key].fileList.map(item => {
                  if (item.response && item.response.success) {
                    file += `${item.response.data},`;
                  }
                  return true;
                });
                newValues[key].inpVal = file ? file.slice(0, file.length - 1) : '';
              }
            }
            newValues[key].pkgPageDetailId = values[key].pageDetailId;
            matlist.push(newValues[key]);
          } else if (key === 'matFlag') {
            accuSerHdl.matFlag = values[key];
          } else if (key === 'copyFiles') {
            accuSerHdl.copyFiles = values[key];
          } else if (key === 'masterFiles') {
            accuSerHdl.masterFiles = values[key];
          }
        });
        const { dispatch, empNameSelect } = this.props;
        const { serTypeId, refundFlag } = this.state;
        accuSerHdl.sendId = empNameSelect[0].sendId;
        accuSerHdl.areaId = empNameSelect[0].areaId;
        accuSerHdl.source = empNameSelect[0].dataSource;
        accuSerHdl.serTypeId = serTypeId;
        accuSerHdl.refundFlag = refundFlag;
        if (+refundFlag === 1) {
          accuSerHdl.payeeBankcardNo = values.payeeBankcardNo;
          accuSerHdl.payeeBankOfDepo = values.payeeBankOfDepo;
          accuSerHdl.payeeName = values.payeeName;
        }
        accuSerHdl.submitFlag = 1;
        const param = {
          matlist,
          accuSerHdl,
        };
        dispatch({
          type: 'accuservicehandle/addCheckList',
          payload: param,
          callback: response => {
            if (response) {
              if (String(response.data.code) === '201') {
                message.error('该员工正在办理此服务类型，不能新增！');
              } else if (String(response.data.code) === '202') {
                confirm({
                  content: '当前人员已办理过此项业务，确定再次办理?',
                  okText: '确定',
                  cancelText: '取消',
                  onOk() {
                    dispatch({
                      type: 'accuservicehandle/addList',
                      payload: param,
                      callback: res => {
                        if (res.success) {
                          router.push(`${tempUrl}/index`);
                        }
                      },
                    });
                  },
                  onCancel() {},
                });
              } else if (String(response.data.code) === '200') {
                router.push(`${tempUrl}/index`);
              }
            }
          },
        });
      }
    });
  };

  // 保存
  save = () => {
    const {
      location: { pathname },
      form,
    } = this.props;
    const tempUrl = pathname.split('/add')[0];
    form.validateFields({ force: true }, (err, values) => {
      if (!err) {
        const matlist = [];
        const accuSerHdl = {};
        const newValues = values;
        Object.keys(values).forEach(key => {
          if (key.indexOf('_') !== -1) {
            if (String(values[key].inpType) === '9') {
              let file = '';
              if (values[key].fileList && values[key].fileList.length) {
                values[key].fileList.map(item => {
                  if (item.response && item.response.success) {
                    file += `${item.response.data},`;
                  }
                  return true;
                });
                newValues[key].inpVal = file ? file.slice(0, file.length - 1) : '';
              }
            }
            newValues[key].pkgPageDetailId = values[key].pageDetailId;
            matlist.push(newValues[key]);
          } else if (key === 'matFlag') {
            accuSerHdl.matFlag = values[key];
          } else if (key === 'copyFiles') {
            accuSerHdl.copyFiles = values[key];
          } else if (key === 'masterFiles') {
            accuSerHdl.masterFiles = values[key];
          }
        });
        const { dispatch, empNameSelect } = this.props;
        const { serTypeId, refundFlag } = this.state;
        accuSerHdl.sendId = empNameSelect[0].sendId;
        accuSerHdl.source = empNameSelect[0].dataSource;
        accuSerHdl.areaId = empNameSelect[0].areaId;
        accuSerHdl.serTypeId = serTypeId;
        accuSerHdl.refundFlag = refundFlag;
        if (+refundFlag === 1) {
          accuSerHdl.payeeBankcardNo = values.payeeBankcardNo;
          accuSerHdl.payeeBankOfDepo = values.payeeBankOfDepo;
          accuSerHdl.payeeName = values.payeeName;
        }

        accuSerHdl.submitFlag = '2';
        const param = {
          matlist,
          accuSerHdl,
        };
        dispatch({
          type: 'accuservicehandle/addCheckList',
          payload: param,
          callback: response => {
            if (response) {
              if (String(response.data.code) === '201') {
                message.error('该员工正在办理此服务类型，不能新增！');
              } else if (String(response.data.code) === '202') {
                confirm({
                  content: '当前人员已办理过此项业务，确定再次办理?',
                  okText: '确定',
                  cancelText: '取消',
                  onOk() {
                    dispatch({
                      type: 'accuservicehandle/addList',
                      payload: param,
                      callback: res => {
                        if (res.success) {
                          router.push(`${tempUrl}/index`);
                        }
                      },
                    });
                  },
                  onCancel() {},
                });
              } else if (String(response.data.code) === '200') {
                router.push(`${tempUrl}/index`);
              }
            }
          },
        });
      }
    });
  };

  // 选择人名
  onSelectData = element => {
    const { elementArr, dispatch } = this.props;
    dispatch({
      type: 'card/matInfor',
      payload: { elementArr, element },
    });
  };

  // 选择人名
  empData = (data, flag) => {
    const { dispatch } = this.props;
    this.setState({
      btnDis: flag,
    });
    dispatch({
      type: 'accuservicehandle/fetchEmpName',
      payload: data,
    });
  };

  // 搜索人名
  empSearch = values => {
    const { dispatch } = this.props;
    dispatch({
      type: 'accuservicehandle/fetchEmpNameList',
      payload: values,
    });
  };

  // 选择身份证号
  idVailFunc = values => {
    const { dispatch } = this.props;
    if (values) {
      dispatch({
        type: 'accuservicehandle/fetchEmpNoList',
        payload: values,
        callback: res => {
          this.setState({
            btnDis: res,
          });
        },
      });
    }
  };

  // 下一步
  next = () => {
    const { dispatch, empNameSelect, form } = this.props;
    const { serTypeId, current } = this.state;
    form.validateFieldsAndScroll({ force: true }, err => {
      if (err) return;
      dispatch({
        type: 'accuservicehandle/checkAccu',
        payload: { sendId: empNameSelect[0].sendId, serTypeId },
        callback: isDisabled => {
          if (isDisabled) {
            this.setState({ visNext: true });
          } else {
            const currentStep = current + 1;
            this.setState({ current: currentStep });
            dispatch({
              type: 'accuservicehandle/fetchMatList',
              payload: {
                serType: 2,
                serTypeId,
                areaId: empNameSelect[0].areaId,
              },
            });
            dispatch({
              type: 'accuservicehandle/fetchSendInfor',
              payload: { areaId: empNameSelect[0].areaId, sendId: empNameSelect[0].sendId, dataSource: empNameSelect[0].dataSource },
            });
          }
        },
      });
    });
  };

  // 下一步
  okNext = () => {
    const { dispatch, empNameSelect } = this.props;
    const { current, serTypeId } = this.state;
    this.setState({ current: current + 1, visNext: false });

    dispatch({
      type: 'accuservicehandle/fetchMatList',
      payload: { serType: 2, serTypeId, areaId: empNameSelect[0].areaId },
    });

    dispatch({
      type: 'accuservicehandle/fetchSendInfor',
      payload: { sendId: empNameSelect[0].sendId, dataSource: empNameSelect[0].dataSource },
    });
  };

  // 取消
  cancelNext = () => {
    this.setState({ visNext: false });
  };

  // 关闭
  close = () => {
    const { location } = this.props;
    const { pathname } = location;
    const tempUrl = pathname.split('/add')[0];
    router.push(`${tempUrl}/index`);
  };

  // 关闭
  close = () => {
    const { location } = this.props;
    const { pathname } = location;
    const tempUrl = pathname.split('/add')[0];
    router.push(`${tempUrl}/index`);
  };

  // 校验
  checkElement = (rule, value, callback) => {
    let tip = '';
    switch (Number(value.inpType)) {
      case 1:
        tip = `请输入不超过30个字的${value.matName}`;
        break;
      case 9:
        tip = `请上传${value.matName}`;
        break;
      case 3:
        tip = `请输入不超过300个字的${value.matName}`;
        break;
      default:
        tip = `请选择${value.matName}`;
        break;
    }
    if (
      +value.inpType !== 9
        ? rule.required && !value.inpVal
        : rule.required && !(value.fileList && value.fileList.length)
    ) {
      callback(tip);
    } else if (+value.inpType === 1 || +value.inpType === 3) {
      if (rule.max < (value.inpVal && value.inpVal.length)) {
        callback(tip);
      } else {
        callback();
      }
    } else {
      callback();
    }
  };

  render() {
    const { current, serTypeName, btnDis, refundFlag, visNext } = this.state;
    const { form } = this.props;
    const { getFieldDecorator } = form;
    const {
      elementArr,
      matFileDictItem,
      sendData,
      serviceTypeList,
      empNameList,
      empNameSelect,
      messageData,
      coltFlag,
      loading,
    } = this.props;
    const { empSendInfoVo, empBaseInfoVo } = sendData;
    const max = val => {
      if (val === 1) return 30;
      if (val === 3) return 300;
      return null;
    };
    const renderElem = elementArrs =>
      elementArrs && elementArrs.length ? (
        elementArrs.map(element => (
          <Row key={element.pageDetailId}>
            <Col span={8}>
              <FormItem {...formItemLayouts} label={<span> {element.matName}</span>}>
                {getFieldDecorator(`mat_${element.pageDetailId}`, {
                  rules: [
                    {
                      required: +element.reqFlag === 1,
                      validator: this.checkElement,
                      max: max(+element.inpType),
                    },
                  ],
                  initialValue: element,
                })(<AddMatInfor onChange={this.onSelectData} />)}
              </FormItem>
            </Col>
          </Row>
        ))
      ) : (
        <div />
      );
    return (
      <PageHeaderWrapper>
        <Card style={{ marginBottom: 12, marginTop: 10 }}>
          <Steps current={current} style={{ width: 327, margin: '0 auto' }}>
            {steps.map(item => (
              <Step key={item.title} title={item.title} />
            ))}
          </Steps>
        </Card>
        <div className={styles.stepsAction}>
          {current === 0 && (
            <Card>
              <FormItem {...formItemLayout} label={<span>服务类型</span>}>
                {getFieldDecorator('serTypeId', {
                  rules: [
                    {
                      required: true,
                      message: '请选择服务类型',
                    },
                  ],
                })(
                  <HOCSelect
                    style={{ width: '100%' }}
                    placeholder="请选择服务类型"
                    // labelInValue
                    showSearch
                    onChange={this.serviceType}
                  >
                    {serviceTypeList &&
                      serviceTypeList.length &&
                      serviceTypeList.map(options => (
                        <Option key={options.serTypeId}>{options.serTypeIdName}</Option>
                      ))}
                  </HOCSelect>
                  // <Select
                  //   style={{ width: '100%' }}
                  //   placeholder="请选择服务类型"
                  //   labelInValue
                  //   showSearch
                  //   onChange={this.serviceType}
                  // >
                  //   {serviceTypeList &&
                  //     serviceTypeList.length &&
                  //     serviceTypeList.map(options => (
                  //       <Option key={options.serTypeId}>{options.serTypeIdName}</Option>
                  //     ))}
                  // </Select>
                )}
              </FormItem>
              <AddEmpForm
                empNameList={empNameList}
                empNameSelect={empNameSelect}
                onSearch={this.empSearch}
                empData={this.empData}
                idVailFunc={this.idVailFunc}
                loading={loading}
              />
              <Row style={{ textAlign: 'center', justifyContent: 'center' }}>
                <Button onClick={this.close}>关闭</Button>
                <Button
                  style={{ marginLeft: 30 }}
                  type="primary"
                  onClick={() => this.next()}
                  disabled={btnDis}
                >
                  下一步
                </Button>
              </Row>
            </Card>
          )}
          {current === 1 && (
            <div>
              <AddEmpInfor
                empSendInfoVo={empSendInfoVo}
                empBaseInfoVo={empBaseInfoVo}
                loading={loading}
              />
              <Card>
                <Card title={<span>业务信息</span>}>
                  <Form layout="inline">
                    <Row>
                      <Col span={8}>
                        <FormItem label="服务类型:">{serTypeName}</FormItem>
                      </Col>
                      <Col span={8}>
                        <FormItem label="是否有返款:">
                          {getFieldDecorator('refundFlag', {
                            rules: [
                              {
                                required: true,
                                message: '请选择是否有返款',
                              },
                            ],
                            initialValue: '2',
                          })(
                            <RadioGroup onChange={this.refunds}>
                              <Radio value="2">无返款</Radio>
                              <Radio value="1">有返款</Radio>
                            </RadioGroup>
                          )}
                        </FormItem>
                      </Col>
                    </Row>
                  </Form>
                  <Form>
                    {+refundFlag === 1 ? (
                      <Row
                        style={{
                          backgroundColor: '#fafafa',
                          height: 60,
                          marginTop: 5,
                        }}
                      >
                        <Col span={8}>
                          <FormItem
                            {...formItemLayouts}
                            label="收款方信息:"
                            style={{
                              marginTop: 10,
                              marginLeft: -20,
                            }}
                          >
                            {getFieldDecorator('payeeName', {
                              rules: [
                                {
                                  required: false,
                                  message: '请输入不超过50个字符的收款方信息',
                                  max: 50,
                                },
                              ],
                            })(<Input placeholder="请输入收款方信息" />)}
                          </FormItem>
                        </Col>

                        <Col span={8} className={styles.triangle}>
                          <FormItem
                            {...formItemLayouts}
                            label="收款方银行账号:"
                            style={{
                              marginTop: 10,
                            }}
                          >
                            {getFieldDecorator('payeeBankcardNo', {
                              rules: [
                                {
                                  required: false,
                                  message: '请输入不超过30个字符的收款方银行账号',
                                  pattern: /^[0-9]{1,30}$/,
                                },
                              ],
                            })(<Input placeholder="请输入收款方银行账号" />)}
                          </FormItem>
                        </Col>

                        <Col span={8}>
                          <FormItem
                            {...formItemLayouts}
                            label="开户行信息:"
                            style={{
                              marginTop: 10,
                            }}
                          >
                            {getFieldDecorator('payeeBankOfDepo', {
                              rules: [
                                {
                                  required: false,
                                  message: '请输入不超过50个字符的开户行信息',
                                  max: 50,
                                },
                              ],
                            })(<Input placeholder="请输入开户行信息" />)}
                          </FormItem>
                        </Col>
                      </Row>
                    ) : null}
                  </Form>
                </Card>

                {String(coltFlag) === '1' && (
                  <div>
                    <Divider />
                    <Form>
                      <div>
                        {matFileDictItem && matFileDictItem.length ? (
                          <div>
                            <Row>
                              <Col span={8}>
                                <FormItem {...formItemLayouts} label="原件材料:">
                                  {getFieldDecorator('masterFiles', {
                                    rules: [
                                      {
                                        required: false,
                                        message: '请选择原件材料',
                                      },
                                    ],
                                  })(
                                    <Select
                                      style={{ width: '100%' }}
                                      mode="multiple"
                                      placeholder="请选择原件材料"
                                      onChange={this.aaa}
                                    >
                                      {matFileDictItem &&
                                        matFileDictItem.length &&
                                        matFileDictItem.map(options => (
                                          <Option key={options.itemCode}>{options.itemName}</Option>
                                        ))}
                                    </Select>
                                  )}
                                </FormItem>
                              </Col>
                            </Row>
                            <Row>
                              <Col span={8}>
                                <FormItem {...formItemLayouts} label="复印件材料:">
                                  {getFieldDecorator('copyFiles', {
                                    rules: [
                                      {
                                        required: false,
                                        message: '请选择复印件材料',
                                      },
                                    ],
                                  })(
                                    <Select
                                      style={{ width: '100%' }}
                                      mode="multiple"
                                      placeholder="请选择复印件材料"
                                    >
                                      {matFileDictItem &&
                                        matFileDictItem.length &&
                                        matFileDictItem.map(options => (
                                          <Option key={options.itemCode}>{options.itemName}</Option>
                                        ))}
                                    </Select>
                                  )}
                                </FormItem>
                              </Col>
                            </Row>
                          </div>
                        ) : null}
                        {renderElem(elementArr)}
                        <div>
                          <Col span={14} offset={1}>
                            <FormItem {...formItemLayouts} label="材料是否完整:">
                              {getFieldDecorator('matFlag', {
                                rules: [
                                  {
                                    required: true,
                                    message: '请选择材料是否完整',
                                  },
                                ],
                              })(
                                <RadioGroup>
                                  <Radio value="1">是</Radio>
                                  <Radio value="2">否</Radio>
                                </RadioGroup>
                              )}
                            </FormItem>
                          </Col>
                        </div>
                      </div>
                    </Form>
                  </div>
                )}
                <Row style={{ textAlign: 'center', justifyContent: 'center' }}>
                  <Button onClick={this.close}>关闭</Button>
                  <Button style={{ marginLeft: 16 }} onClick={() => this.prev()}>
                    上一步
                  </Button>
                  <Button style={{ marginLeft: 16 }} type="primary" onClick={() => this.save()} loading={loading}>
                    保存
                  </Button>
                  <Button
                    style={{ marginLeft: 16 }}
                    type="primary"
                    onClick={() => this.saveUpdate()}
                    loading={loading}
                  >
                    保存并提交运行
                  </Button>
                </Row>
              </Card>
            </div>
          )}
        </div>
        <Modal title="提示" visible={visNext} onOk={this.okNext} onCancel={this.cancelNext}>
          <p>{Object.keys(messageData).length ? messageData : null}</p>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}
const archivesAddform = Form.create()(archivesAdd);
export default archivesAddform;
